package com.heima.user.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.admin.pojos.ApUserRealname;
import com.heima.model.common.dtos.PageSensitive;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.user.Dto.LoginDto;
import com.heima.model.common.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApUserServiceimp extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Override
    public ResponseResult log(LoginDto dto) {
        if (StringUtils.isNotBlank(dto.getPassword()) && StringUtils.isNotBlank(dto.getPhone())) {
            LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUser::getPhone, dto.getPhone());
            ApUser apUser = getOne(queryWrapper);
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "大哥，的用户名不存在");
            }
            //获取盐
            String salt = apUser.getSalt();
            //获取前端传过来的密码
            String password = dto.getPassword();
            //根据MD5进行解密
            String pass = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if (!pass.equals(apUser.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "大哥，你的密码错了");
            }
            //生成token
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", token);
            apUser.setSalt("");
            apUser.setPassword("");
            map.put("user", apUser);
            return ResponseResult.okResult(map);
        }
        //游客登录
        Map<String, Object> map = new HashMap<>();
        map.put("token", AppJwtUtil.getToken(0l));
        return ResponseResult.okResult(map);

    }

//    @Override
//    public ResponseResult userlist(PageSensitive pageSensitive) {
//        Page<ApUserRealname> page = new Page<>(pageSensitive.getPage(),pageSensitive.getSize());
//        Page<ApUser> userPage = this.page(page);
//        List<ApUser> records = userPage.getRecords();
//        return ResponseResult.okResult(records);
//    }
}
